package net.thxjj.netty;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import net.model.TypeCmd;
import net.model.device.*;
import net.model.deviceresp.DevRespBean;
import net.thxjj.error.ActionType;
import net.thxjj.error.ErrCode;
import net.util.ParameterMap;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;


public class DeviceSendHandler extends HeartBeatBaseChannelInBoundHandler {

    private Logger log = Logger.getLogger(String.valueOf(this.getClass()));

    /**
     *channelRead0
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, BaseBean s) throws Exception {

    }

    /**
     * channelRead
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx,msg);
        if(!DeviceSocketMap.hasDevice(ctx.channel())){
            ctx.close();
            return;
        }
        try {
            String de = (String)msg;
            CmdBean cmdBean =  JSONObject.parseObject(de, CmdBean.class);
            log.info("收到命令数据："+cmdBean.toString());

            //params字段缺失报错
            if(cmdBean.getParams()==null){
                DevRespBean devRespBean =  new DevRespBean(cmdBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.PARAMS_IS_NOT_EXIST_ERROR.getCode(),ErrCode.PARAMS_IS_NOT_EXIST_ERROR.getDescription(),null);
                ctx.writeAndFlush(devRespBean.toString());
                ctx.close();
                return;
            }

            CmdParams params = cmdBean.getParams();

            //params内data字段缺失报错
            if(params.getData()==null){
                DevRespBean devRespBean =  new DevRespBean(cmdBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.DATA_CAN_NOT_EMPTY_ERROR.getCode(),ErrCode.DATA_CAN_NOT_EMPTY_ERROR.getDescription(),null);
                ctx.writeAndFlush(devRespBean.toString());
                ctx.close();
                return;
            }

            HashMap<String,Object> map = params.getData();
            //data字段属性字段必填项cmdId缺失报错
            if(!map.containsKey("cmdId")){
                DevRespBean devRespBean =  new DevRespBean(cmdBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.CMDID_CAN_NOT_EMPTY_ERROR.getCode(),ErrCode.CMDID_CAN_NOT_EMPTY_ERROR.getDescription(),null);
                ctx.writeAndFlush(devRespBean.toString());
                return;
            }
            AttributeKey<String> key = AttributeKey.valueOf("prodKey");
            String prodKey = ctx.channel().attr(key).get();
            Integer cmdid = (Integer) map.get("cmdId");
           ParameterMap property = productService.getProductPropertys(cmdid, prodKey, TypeCmd.TYPE_DEV_SEND);

           //判断是否含有cmdId关键字段
           if(property==null){
               DevRespBean devRespBean =  new DevRespBean(cmdBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.INSTRUCTION_NOT_EXIST_ERROR.getCode(),ErrCode.INSTRUCTION_NOT_EXIST_ERROR.getDescription(),null);
               ctx.writeAndFlush(devRespBean.toString());
               return;
           }

           String content = (String)property.get("content");
           if(StringUtils.isEmpty(content)){
               DevRespBean devRespBean =  new DevRespBean(cmdBean.getMsgId(), ActionType.DEVICE_SENDRESP.getName(), ErrCode.INSTRUCTION_NOT_EXIST_ERROR.getCode(),ErrCode.INSTRUCTION_NOT_EXIST_ERROR.getDescription(),null);
               ctx.writeAndFlush(devRespBean.toString());
               return;
           }

           //判断上报的数据是否合法
           ErrCode flag = productService.isLawFul(content,map);
            DevRespBean devRespBean =  new DevRespBean(cmdBean.getMsgId(), flag == ErrCode.SUCCESS?ActionType.DEVICE_SENDRESP.getName():ActionType.ERROR_RESP.getName(), flag.getCode(),flag.getDescription(),null);
            ctx.writeAndFlush(devRespBean.toString());

            //记录日志并实时发送
            if(flag==ErrCode.SUCCESS){
                ParameterMap parameterMap = new ParameterMap();
                parameterMap.put("device_id",params.getDevTid());
                parameterMap.put("log_type",1);
                parameterMap.put("content",de);
                parameterMap.put("create_time",System.currentTimeMillis());
                deviceService.insertDevSendLog(parameterMap);

                List<Long> listusers = deviceService.getRelationUserIds(params.getDevTid());
                if(listusers!=null && listusers.size()>0){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("users",listusers);
                    jsonObject.put("devInfo",cmdBean);
                    mobileWebSocketClient.sendWebsocket(jsonObject.toJSONString());
                }


            }

        }catch (JSONException e){
            e.printStackTrace();
            ctx.close();
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
